package com.pxxy.lawconsult.servlet;

import java.io.IOException;
import java.io.PrintWriter;
import java.sql.ResultSet;
import java.util.HashMap;
import java.util.Map;

import javax.servlet.ServletException;
import javax.servlet.annotation.WebServlet;
import javax.servlet.http.HttpServlet;
import javax.servlet.http.HttpServletRequest;
import javax.servlet.http.HttpServletResponse;

import com.google.gson.Gson;
import com.pxxy.lawconsult.bean.User;
import com.pxxy.lawconsult.constant.DBConstant;
import com.pxxy.lawconsult.utils.DBUtils;

@WebServlet("/IsUserExistServlet")
public class IsUserExistServlet extends HttpServlet {
	private static final long serialVersionUID = 1L;

	public static final String IS_REGISTER = "isUserExist";// json账号是否存在:key
	public static final String ISREGISTER_EXIST = "exist";// json账号是否存在:value
	public static final String ISREGISTER_NOT_EXIST = "notExist";// json账号是否存在:value
	public static final String ISREGISTER_SERVERERROR= "serverError";//json账号是否存在:value
	

	private Gson gson;
	private Map<String, String> map;

	public IsUserExistServlet() {
		super();
	}

	protected void doGet(HttpServletRequest request, HttpServletResponse response)
			throws ServletException, IOException {
		doPost(request, response);
	}

	protected void doPost(HttpServletRequest request, HttpServletResponse response)
			throws ServletException, IOException {
		String tel = request.getParameter(User.TEL);
		gson = new Gson();
		map = new HashMap<>();

		if (tel == null || tel.equals("")) {
			return;
		}
		
		PrintWriter out = response.getWriter();
		try {
			// 先查询用户是否存在
			ResultSet resultSet = DBUtils.query(DBConstant.TB_USER_TABLE, DBConstant.USER_TABLE_TEL, tel);
			if (resultSet.next()) {
				map.put(IS_REGISTER, ISREGISTER_EXIST);
				return;
			}else {
				map.put(IS_REGISTER, ISREGISTER_NOT_EXIST);
			}
		} catch (Exception e) {
			map.put(IS_REGISTER, ISREGISTER_SERVERERROR);
			e.printStackTrace();
		}finally {
			String isRegisterJson = gson.toJson(map);
			out.println(isRegisterJson);
			out.close();
			DBUtils.close();
		}

	}

}
